#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime

import tornado
import tornado.web
from utils import log
import json
import re
from config import etc
from controls import data_topic_note_img_mysql
from controls import data_topic_note_like_mysql
from controls import data_topic_note_mysql
from controls import data_user_brief_mysql
from controls import data_user_feed_mysql
from controls import data_topic_title_mysql
from controls import mongo
from controls import data_img_base_mysql
from utils.file_util import img_file_upload, get_100_size_imglink
from utils.session_base import ApiGuest, ApiHost
from utils.session_mc import BaseHandler

class ListHandler(BaseHandler):
    @ApiGuest
    def post(self, *args, **kwargs):
        topicid = self.ss_params['topicid']
        begin = self.ss_params.get('begin', 0)
        limit = self.ss_params.get('limit', 20)
        except_list = self.ss_params.get('except', [])

        if topicid and begin and limit is None:
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return

        note_list = data_topic_note_mysql\
            .get_topic_note_by_topicid(topicid, begin, limit, except_list)
        noteid_list = [item['noteid'] for item in note_list]
        userid_list = [item['userid'] for item in note_list]

        topic_title = data_topic_title_mysql.get_topic_title_by_topicid(topicid)
        note_img_list = data_topic_note_img_mysql.get_topic_note_img_by_noteid_list(noteid_list)
        # log.i("*** note_img_list: %s ***" % note_img_list)
        #imgid_list = [item['imgid'] for item in note_img_list]

        all_imgid_list = []
        note_img_list_map = {}
        for item in note_img_list:
            all_imgid_list += item['imgid']
            note_img_list_map[item['noteid']] = item['imgid']

        # log.i("*** all_imgid_list: %s ***" % all_imgid_list)

        note_img_map = data_img_base_mysql.get_img_url_by_imgid_list(all_imgid_list)

        # log.i("*** note_img_map: %s ***" % note_img_map)

        user_brief_map = data_user_brief_mysql\
            .get_user_brief_map_by_userid_list(userid_list)
        note_like_count_map = data_topic_note_like_mysql\
            .get_note_like_count_map_by_noteid_list(noteid_list)

        for item1 in note_list:
            noteid = item1['noteid']
            userid = item1['userid']
            item1['user'] = user_brief_map[userid]
            item1['user']['thumblink'] = item1['user']['imglink'][0:len(item1['user']['imglink'])-1] + '132'
            item1['like_count'] = note_like_count_map.get(noteid, 0)
            item1['imgs'] = []
            item1['thumbs'] = []
            item1['topic'] = topic_title['title']
            temp_img_list = note_img_list_map.get(noteid, [])
            for item2 in temp_img_list:
                if item2 in note_img_map.keys():
                    item1['imgs'].append(note_img_map[item2])
                    item1['thumbs'].append(re.sub("(.*)(\.[a-z0-9]{1,4})$", r"\1_100\2", note_img_map[item2]))

        # current_user liked notes
        if self.current_user:
            userid = self.current_user['userid']
            user_like_list = data_topic_note_like_mysql\
                .get_note_like_by_noteid_list_and_userid(noteid_list, userid)
            for item in note_list:
                if item['noteid'] in user_like_list:
                    item['liked'] = 1
                else:
                    item['liked'] = 0
        else:
            for item in note_list:
                item['liked'] = 0

        # log.i(note_list)
        res = {'idx': self.ss_idx, 'ret': 0, 'msg': '获取成功', 'res': note_list}
        self.write(json.dumps(res))
        self.finish()
        return


class ListOneHandler(BaseHandler):
    @ApiHost
    def post(self):
        noteid = self.ss_params.get('noteid')

        if not noteid:
            log.w('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        note_item = data_topic_note_mysql.get_topic_note_by_noteid(noteid)

        if not note_item:
            log.w('noteid error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': 'noteid error', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        topic_title = data_topic_title_mysql.get_topic_title_by_topicid(note_item['topicid'])
        note_img = data_topic_note_img_mysql.get_topic_note_img_by_noteid(noteid)
        note_imgid_list = note_img['imgid']

        note_img_map = data_img_base_mysql\
            .get_img_url_by_imgid_list(note_imgid_list)

        note_item['imgs'] = []
        note_item['thumbs'] = []
        for i in note_imgid_list:
            if i in note_img_map.keys():
                note_item['imgs'].append(note_img_map[i])
                note_item['thumbs'].append(get_100_size_imglink(note_img_map[i]))

        user_brief = data_user_brief_mysql\
            .get_user_brief_by_userid(note_item['userid'])

        note_item['user'] = user_brief
        note_item['user']['thumblink'] =\
            note_item['user']['imglink'][0:len(note_item['user']['imglink'])-1]\
            + '132'
        note_item['topic'] = topic_title['title']
        like_count = data_topic_note_like_mysql\
            .get_note_like_count_by_noteid(noteid)
        note_item['like_count'] = like_count

        if self.current_user:
            liked = data_topic_note_like_mysql\
                .get_topic_note_like_by_noteid_and_userid(
                    noteid,
                    self.current_user['userid'],
                )

            if liked:
                note_item['liked'] = 1
            else:
                note_item['liked'] = 0
        else:
            note_item['liked'] = 0

        res = {'idx': self.ss_idx, 'ret': 0, 'msg': '获取成功', 'res': note_item}
        self.write(json.dumps(res))
        self.finish()
        return


class LikePostHandler(BaseHandler):
    @ApiHost
    def post(self):
        noteid = self.ss_params['noteid']
        userid = self.ss_user['userid']

        if not (noteid and userid):
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        item = {
            'userid': userid,
            'noteid': noteid
        }

        note_like = data_topic_note_like_mysql.get_topic_note_like_by_noteid_and_userid(noteid, userid)

        if note_like is None:
            data_topic_note_like_mysql.add_topic_note_like_item(item)
            if not data_user_feed_mysql.add_user_feed_item({
                'userid': userid,
                'optype': data_user_feed_mysql.USER_FEED_TYPE_NOTE_LIKE,
                'targetid': noteid,
            }):
                self._generate_res(1, '收藏失败', 'add_note_like_feed')
                return
        else:
            result = {
                'liked': 1
            }
            res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': result}
            self.write(json.dumps(res))
            self.finish()
            return

        result = {
            'liked': 1,
        }
        res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': result}
        self.write(json.dumps(res))
        self.finish()
        return

class DelPostLikeHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        noteid = self.ss_params['noteid']
        userid = self.ss_user['userid']

        if not (noteid and userid):
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        data_topic_note_like_mysql.del_topic_note_like_by_noteid_and_userid(noteid, userid)
        if not data_user_feed_mysql.del_user_feed({
            'userid': userid,
            'optype': data_user_feed_mysql.USER_FEED_TYPE_NOTE_LIKE,
            'targetid': noteid,
        }):
            self._generate_res(1, '删除动态失败', 'add_note_like_feed')
            return
        # note = data_topic_note_mysql.get_topic_note_by_noteid(noteid)
        result = {
            'liked': 0
        }
        res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': result}
        self.write(json.dumps(res))
        self.finish()
        return

class PostHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        userid = self.ss_user['userid']
        topicid = self.ss_params['topicid']
        note = self.ss_params['note']
        tags = self.ss_params['tags']
        place = self.ss_params['place']

        if not topicid:
            log.w('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        try:
            imgid_list = []

            if not (note or self.request.files):
                log.i('add note img error')
                self._generate_res(1, "请添加note或图片")
                return

            for i in xrange(len(self.request.files)):
                tmp_file = self.request.files[("file[%s]" % i)][0]
                file_res = img_file_upload(tmp_file)

                if file_res and file_res['ret'] == 0:
                    imgid_list.append(str(file_res['res']['imgid']))

            noteid = mongo.count_noteid()

            new_note_item = {
                'topicid': topicid,
                'noteid': noteid,
                'note': note,
                'complete': 0,
                'userid': userid,
                'tags': tags,
                'place': place
            }

            if not data_topic_note_mysql\
                    .add_topic_note_item(new_note_item):
                log.i('add note img error')
                self._generate_res(1, "添加note失败")
                return

            if not data_user_feed_mysql.add_user_feed_item({
                'userid': userid,
                'optype': data_user_feed_mysql.USER_FEED_TYPE_NOTE_POST,
                'targetid': noteid,
            }):
                self._generate_res(1, '收藏失败', 'add_note_post_feed')
                return

            new_img_item = {
                'topicid': topicid,
                'noteid': noteid,
                'imgid': imgid_list,
            }
            if not data_topic_note_img_mysql\
                    .add_topic_note_img_item(new_img_item):
                log.i('add note img error')
                self._generate_res(1, "添加图片失败")
                return

            log.i('pulish note success')
            self._generate_res(0, "发布成功")
            return

        except Exception as e:
            log.exp(e)
            self._generate_res(1, etc.err_500, 'note_post')
            return

class ApiNotFindHandler( BaseHandler ) :

    def get( self ):
        raise tornado.web.HTTPError( 503 )
    @tornado.web.asynchronous
    def post( self ):
        log.i( self  )
        res = { 'idx':0, 'ret':9, 'msg':'无此功能', 'res':{} }
        self.write( json.dumps(res) )
        self.finish()